package com.yunshang.shoppingmall.shopping.OrderController;

import com.alibaba.fastjson.JSON;
import com.yunshang.shoppingmall.common.MessageConstants;
import com.yunshang.shoppingmall.common.OrderHelper;
import com.yunshang.shoppingmall.common.Response;
import com.yunshang.shoppingmall.common.weixin.AmountUtils;
import com.yunshang.shoppingmall.entity.*;
import com.yunshang.shoppingmall.service.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.math.BigDecimal;
import java.text.DecimalFormat;
import java.util.*;

import static com.yunshang.shoppingmall.common.OrderHelper.*;

@RequestMapping("/wap")
@Controller
public class SureOrderController {
    @Autowired
    CartService cartService;
    @Autowired
    OrderService orderService;
    @Autowired
    OrderDetailsService orderDetailsService;
    @Autowired
    AddressService addressService;
    @Autowired
    OrderAddressService orderAddressService;

    //001确认订单-购物车
    @ResponseBody
    @RequestMapping("/getSureCartList")
    public ModelAndView getSureCartList(HttpServletRequest request) {
        String cartids = request.getParameter("cartids");
        String ss="["+cartids+"]";
        double sum=0;
        List<String> cartidsList =  JSON.parseArray(ss.toString(), String.class);
        HttpSession session = request.getSession();
        UserNo userNo1 = (UserNo) session.getAttribute("userNo");
        int memberUserId = 0;
        int memberLevel=0;
        if (userNo1 != null) {
            memberUserId = userNo1.getId();
            memberLevel= userNo1.getRank();
        }
        List<OrderDetailsProduct> list = orderDetailsService.selectCart(memberUserId+"",cartidsList);
        Map<String, Object> map = operOrderDetailsProduct(list,memberLevel,memberUserId);
        ModelAndView modelAndView=new ModelAndView("shoppingApi/order/orderSure");
        for (int i = 0; i <list.size() ; i++) {
          BigDecimal price= list.get(i).getProductPrice();
          Integer count=list.get(i).getProductCount();
         double priceTotal= price.doubleValue()*count.intValue();
         sum+=priceTotal;
        }
        map.put("proPrice",sum);
        modelAndView.addObject("orderSure",map);
        return  modelAndView;
    }

    @ResponseBody
    @RequestMapping("/addOrder")
    //生成订单
    public Response addOrder(HttpServletRequest request){
        //判断登录
        if(!com.yunshang.shoppingmall.common.loginOut.checkLogin(request)) {
            return new Response(MessageConstants.MSG_SYS_ERROR,-2,"");
        }
        DecimalFormat df = new DecimalFormat("#0");//显示格式
        String carts = request.getParameter("carts");
        String ss="["+carts+"]";
        int addressids=0;
        String addressStr = request.getParameter("addressStr");
        String addressId = request.getParameter("addressId");
        String coupon = request.getParameter("coupon");
        String cashcoupon = request.getParameter("cashcoupon");
        String realPay = request.getParameter("realPay");
        String freight = request.getParameter("freight");
        String memberSave = request.getParameter("memberSave");
        String backCashCoupon = request.getParameter("backCashCoupon");
        List<String> cartidsList = JSON.parseArray(ss, String.class);
        Date d = new Date();
        BigDecimal oprator_cost=BigDecimal.ZERO;//运营成本
        Double product_cost=0.00;//产品成本

        Double avaCoupon=0.00;//可用购物券
        Integer avaCashcoupon=0;//可用代金券
        BigDecimal order_money=BigDecimal.ZERO;//订单金额
        Double weight=0.0;//重量
        double activityInter=0,activityCostinter=0,activityCoupon=0,activityCashcoupon=0;//活动积分 消费积分 购物券 代金券

        java.text.DateFormat format2 = new java.text.SimpleDateFormat("yyyyMMddHHmmss");
        String orderString = format2.format(new Date());
        int intRandom=(int)(1+Math.random()*(10-1+1)*1000);
        Order order=new Order();
        String OrderNo="D"+orderString+intRandom;
        order.setOrderNo(OrderNo);
        order.setStoreId(1);//店铺ID
        order.setOrderStatus("701");
        order.setIsOrderFrom(0);
        Double backCashCouponDouble=0.00;
        try {
            backCashCouponDouble=Double.parseDouble(backCashCoupon);
        }catch (Exception e){
        }
        order.setBackCashcoupon(backCashCouponDouble);
        //用户信息
        int memberLevel=0;
        int memberUserId=0;

        HttpSession session = request.getSession();
        UserNo userNo1 = (UserNo)session.getAttribute("userNo");
        if(userNo1!=null) {
            memberLevel= userNo1.getRank();
            memberUserId=userNo1.getId();//用户编号id
        }
        /*根据购物车ID查出产品中的运营成本
         */
        List<OrderDetailsProduct> cartList=orderDetailsService.selectProductDetailsByCartID(cartidsList);//从前台传数据过来
        if(cartidsList==null){
            return new Response(MessageConstants.MSG_SYS_ERROR,-1,"购物车数据有误,生成失败!");
        }

        int guigeid=0;
        int count=0;
        String supplier="";
        for (OrderDetailsProduct cart:cartList){
            //单次购买限制1
            if(!supplier.equals("四川若禺")){
                supplier=cart.getSupplier()==null?"":cart.getSupplier();
            }

            if(guigeid!=505) {
                guigeid = cart.getGuigeId() == null ? 0 : cart.getGuigeId();
            }
            if(guigeid==505){
                order.setComment("1");
                count=cart.getProductCount()==null?2:cart.getProductCount();
            }
            //单次购买限制

            BigDecimal opratorCostA=cart.getOpratorCost();
            BigDecimal productCostA=cart.getProductCost();
            BigDecimal couponA=cart.getCoupon();
            int productCountA=cart.getProductCount();
            BigDecimal productPriceA=cart.getProductPrice();
            int visitorA=cart.getVisitor();
            int huiyuanA=cart.getHuiyuan();
            int dianzhuA=cart.getDianzhu();
            int yYzDianzhuA=cart.getYzDianzhu();
            int otherRankA=cart.getOtherRank();

            weight +=cart.getProWeight();
            BigDecimal opcostall=BigDecimal.valueOf(opratorCostA.doubleValue()*productCountA);
            double prcostall=productCostA.doubleValue()*productCountA;
            oprator_cost =oprator_cost.add(opcostall);
            product_cost +=prcostall;
            avaCoupon +=couponA.doubleValue()*productCountA;
            BigDecimal tempOrderMoney=BigDecimal.valueOf(productPriceA.doubleValue()*productCountA);
            order_money =order_money.add(tempOrderMoney);
            avaCashcoupon +=discount(memberLevel,visitorA,huiyuanA,dianzhuA,yYzDianzhuA,otherRankA)*productCountA;
            activityInter +=huiyuanA*productCountA;
            activityCoupon +=otherRankA*productCountA;
            activityCashcoupon +=visitorA*productCountA;
            activityCostinter +=dianzhuA*productCountA;
        }

        //购买一次
        if(guigeid==505) {
            List<Order> order1 = orderService.selectOrderActivityOne(memberUserId + "");
            if (order1 != null && order1.size() > 0) {
                return new Response(MessageConstants.MSG_SYS_ERROR, -3, "当前产品限购数量1次!");
            }else if(count>1){
                return new Response(MessageConstants.MSG_SYS_ERROR, -3, "当前产品限购数量1次!");
            }
        }
        //购买一次

        // double activityInter=0,activityCostinter=0,activityCoupon=0,activityCashcoupon=0;//活动积分 消费积分 购物券 代金券
        //活动赠送货币
        //会员-积分 游客-代金券 其他等级-购物券


        //订单最小利润
        double minProfit=order_money.doubleValue()-Double.parseDouble(coupon)-Double.parseDouble(cashcoupon)-product_cost-oprator_cost.doubleValue();
        order.setOrderProfit(minProfit);//订单最小利润

        order.setActivityInter(activityInter);//活动积分
        order.setActivityCoupon(activityCoupon);//活动购物券
        order.setActivityCashcoupon(activityCashcoupon);//活动代金券
        order.setActivityCostinter(activityCostinter);//活动消费积分

        order.setOrderMoney(order_money);// 订单金额 通过产品价格来计算
        order.setOpratorCost(oprator_cost);//运营成本
        order.setProductCost(product_cost);//产品成本
        order.setUserId(memberUserId);//用户编号id
        order.setCoupon(BigDecimal.valueOf(Double.parseDouble(coupon)));//购物券 从前台传数据过来 当前订单抵扣使用多少
        order.setCashCoupon(BigDecimal.valueOf(Double.parseDouble(cashcoupon)));//代金券 从前台传数据过来 当前订单抵扣使用多少
        order.setpOrderTime(d);

        /*获取运费*/
        order.setFreight(BigDecimal.valueOf(Double.parseDouble(freight)));
        order.setRealPay(Double.valueOf(realPay));
        order.setMemberSave(Double.valueOf(memberSave));
        /*获取可用购物券和可用代金券
         */
        order.setAvaCoupon(BigDecimal.valueOf(avaCoupon));
        order.setAvaCashcoupon(avaCashcoupon);
        //

        order.setLogisticalType(2);//前台传值
            if(addressId!=null&&!"".equals(addressId)){
               addressids= Integer.parseInt(addressId);
            }
            Address address=addressService.selectByPrimaryKey(addressids);
            if(address!=null){
                if(supplier.equals("四川若禺")){
                    boolean boos= OrderHelper.checkArea(address.getProvinceId()==null?"0":address.getProvinceId()+"","23,26,29,31");
                    if(boos){
                        return new Response(MessageConstants.MSG_SYS_ERROR, -5, "当前产品不支持发往当前地址!");
                    }
                }
            }
            OrderAddress orderAddress=new OrderAddress();
            orderAddress.setProvinceId(address.getProvinceId());
            orderAddress.setCityId(address.getCityId());
            orderAddress.setUserId(address.getUserId());
            orderAddress.setAreaId(address.getAreaId());
            orderAddress.setName(address.getName());
            orderAddress.setPhone(address.getPhone());
            orderAddress.setDetailAddr(address.getDetailAddr());
            orderAddress.setLogType(2);//2 快递
            orderAddress.setRemark(addressStr);
        int orderAddressId=0,reso1=0;
        OrderAddress orderAddress1=orderAddressService.selectByOrderAddress(orderAddress);
        if(orderAddress1!=null){
            orderAddressId=orderAddress1.getId();
        }else {
            reso1 = orderAddressService.insertSelective(orderAddress);
        }
        if (reso1 > 0) {
            orderAddressId=orderAddress.getId();
        }
        order.setAddressId(orderAddressId);//地址id
        int res=orderService.insert(order);//生成订单
        if(res>=1){
            int ss1=addressService.updateAddressIsMoreAddressByUserId(memberUserId);
//            Address address1=addressService.selectDefault(1,memberUserId);
//            address1.setIsMoreAddress(1);
//            addressService.updateByPrimaryKey(address1);
            //1870,1;1871,1;1872,2 活动多个地址
            //System.out.println("cartidsList.size():"+cartidsList.size());
            if(cartList!=null&&cartidsList.size()==1){
//                OrderDetailsProduct orderDetailsProduct=cartList.get(0);
//                int productid=orderDetailsProduct.getProductId()==null?0:orderDetailsProduct.getProductId();
//                int guigeid=orderDetailsProduct.getGuigeId()==null?0:orderDetailsProduct.getGuigeId();
//                int usernoid=orderDetailsProduct.getUserId()==null?0:orderDetailsProduct.getUserId();
//                int productcount=orderDetailsProduct.getProductCount()==null?0:orderDetailsProduct.getProductCount();
                Cart cart=cartService.selectByPrimaryKey(Integer.parseInt(carts));
                addressStr=addressStr==null?"":addressStr;
                String []strs=null;
                if(!addressStr.equals("")){
                    strs=addressStr.split(";");
                }
                int i=0;
                List<String> list=new ArrayList<>();
                if(strs!=null) {
                    for (String str : strs) {
                        if (!"".equals(str)) {
                            String[] strs1 = str.split(",");
                            if (strs1.length == 2) {
                                int adid = 0, adnumber = 0;
                                try {
                                    adid = Integer.parseInt(strs1[0]);
                                    adnumber = Integer.parseInt(strs1[1]);
                                } catch (Exception e) {
                                }

                                Address addressQ = addressService.selectByPrimaryKey(adid);
                                OrderAddress orderAddressQ = new OrderAddress();
                                orderAddressQ.setProvinceId(addressQ.getProvinceId());
                                orderAddressQ.setCityId(addressQ.getCityId());
                                orderAddressQ.setUserId(addressQ.getUserId());
                                orderAddressQ.setAreaId(addressQ.getAreaId());
                                orderAddressQ.setName(addressQ.getName());
                                orderAddressQ.setPhone(addressQ.getPhone());
                                orderAddressQ.setDetailAddr(addressQ.getDetailAddr());
                                orderAddressQ.setLogType(2);//2 快递
                                //orderAddressQ.setRemark(addressStr);
                                int orderAddressIdQ = 0, reso1Q = 0;
                                OrderAddress orderAddress1Q = orderAddressService.selectByOrderAddress(orderAddressQ);
                                if (orderAddress1Q != null) {
                                    orderAddressIdQ = orderAddress1Q.getId();
                                } else {
                                    reso1Q = orderAddressService.insertSelective(orderAddressQ);
                                }
                                if (reso1Q > 0) {
                                    orderAddressIdQ = orderAddressQ.getId();
                                }
                                if (i == 0) {
                                    if (adnumber > 0) {
                                        cart.setProductCount(adnumber);
                                        cart.setAddressId(orderAddressIdQ);
                                        cartService.updateByPrimaryKeySelective(cart);
                                    }
                                } else {
                                    if (adnumber > 0) {
                                        Cart cart1 = new Cart();
                                        cart1.setProductId(cart.getProductId());
                                        cart1.setGuigeId(cart.getGuigeId());
                                        cart1.setUserId(cart.getUserId());
                                        cart1.setCartStatus(cart.getCartStatus());
                                        cart1.setOrderNo(cart.getOrderNo());
                                        cart1.setTime(cart.getTime());
                                        cart1.setType(cart.getType());
                                        cart1.setAddressId(orderAddressIdQ);
                                        cart1.setProductCount(adnumber);
                                        cartService.insert(cart1);
                                        cartidsList.add(cart1.getShoppingId().toString());
                                    }
                                }
                            }
                        }
                        i++;
                    }
                }
                //cartService.upCartStatus(list,OrderNo);
            }
            Integer res1=cartService.upCartStatus(cartidsList,OrderNo);//更新购物车的状态
            return new Response(MessageConstants.MSG_SUCCESS,OrderNo,"生成成功!");
        } else {
            return new Response(MessageConstants.MSG_SYS_ERROR,res,"生成失败!");
        }
    }
    //确认订单（直接购买）
    @ResponseBody
    @RequestMapping("/directAddOrder")
    public ModelAndView directAddOrder(HttpServletRequest request,Integer productId,Integer guigeId,Integer productCount) {
        Response response;int cartId;
        ModelAndView modelAndView=new ModelAndView("shoppingApi/order/directOrderSure");
        HttpSession session = request.getSession();
        UserNo userNo1 = (UserNo)session.getAttribute("userNo");
        int memberUserId=0;int memberLevel=0;
        if(userNo1!=null){//已经登录
            memberUserId=userNo1.getId();//用户编号id
            memberLevel= userNo1.getRank();
        }
            Cart cart=cartService.selectCart(productId,guigeId,memberUserId);
        if (cart==null) {
            response = addCartPub(productId, guigeId, productCount, memberUserId );//添加购物车
            cartId=(int)response.getData();
        }else {
            upCartPub(cart.getShoppingId(),productCount);
            cartId=cart.getShoppingId();
        }
            OrderDetailsProduct orderDetailsProduct=orderDetailsService.selectCartOne(memberUserId,cartId);


       // List<String> carts=new ArrayList<>();
       // carts.add(cartId+"");
            List<OrderDetailsProduct> list=new ArrayList<>();
            list.add(orderDetailsProduct);
            Map<String, Object> map = operOrderDetailsProduct(list,memberLevel,memberUserId);
            modelAndView.addObject("directOrderSure",map);
            return  modelAndView;
    }

    //直接购买加入购物车
    @ResponseBody
    @RequestMapping("/addCartS")
    public Response addCartS(HttpServletRequest request,Integer productId,Integer guigeId,Integer productCount)
    {
        HttpSession session = request.getSession();
        UserNo userNo1 = (UserNo)session.getAttribute("userNo");
        int memberUserId=0;
        int memberLevel=0;
        if(userNo1!=null)
        {
            memberUserId=userNo1.getId();
            memberLevel= userNo1.getRank();
        }
        Response response=addCartPub(productId,guigeId,productCount,memberUserId);
        return  response;
    }

    @ResponseBody
    @RequestMapping("/setCartNumber")
    public Map<String,Object> setCartNumber(HttpServletRequest request,Integer shoppingId,Integer number)
    {
        HttpSession session = request.getSession();
        UserNo userNo1 = (UserNo) session.getAttribute("userNo");
        int memberUserId = 0,memberLevel=0;
        if (userNo1 != null) {
            memberUserId = userNo1.getId();
            memberLevel= userNo1.getRank();
        }
        Map<String, Object> map=new HashMap<>();
        Cart cart=cartService.selectByPrimaryKey(shoppingId);
        cart.setProductCount(number);
        int res=cartService.updateByPrimaryKey(cart);
        if(res>0){
            String ss="["+shoppingId+"]";
            List<String> cartidsList =  JSON.parseArray(ss, String.class);
            List<OrderDetailsProduct> list = orderDetailsService.selectCart(memberUserId+"",cartidsList);
            map = operOrderDetailsProduct(list,memberLevel,memberUserId);
            return map;
        }
        return map;
    }
}
